package com.hmall.item.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.service.IItemService;
import com.hmall.common.domain.PageDTO;
import com.hmall.common.domain.PageQuery;
import com.hmall.common.utils.BeanUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "商品管理相关接口")
@RestController
@RequestMapping("/items")
@RequiredArgsConstructor
@Slf4j
public class ItemController {

    private final IItemService itemService;

    private final RabbitTemplate rabbitTemplate;

    @ApiOperation("分页查询商品")
    @GetMapping("/page")
    public PageDTO<ItemDTO> queryItemByPage(PageQuery query) {
        // 1.分页查询
        Page<Item> result = itemService.page(query.toMpPage("update_time", false));
        // 2.封装并返回
        return PageDTO.of(result, ItemDTO.class);
    }

    @ApiOperation("根据id批量查询商品")
    @GetMapping
    public List<ItemDTO> queryItemByIds(@RequestParam("ids") List<Long> ids) {
        //  模拟业务延迟
        ThreadUtil.sleep(500);
        return itemService.queryItemByIds(ids);
    }

    @ApiOperation("根据id查询商品")
    @GetMapping("{id}")
    public ItemDTO queryItemById(@PathVariable("id") Long id) {
        return BeanUtils.copyBean(itemService.getById(id), ItemDTO.class);
    }

    @ApiOperation("新增商品")
    @PostMapping
    public void saveItem(@RequestBody ItemDTO item) {
        // 将ItemDTO转换为Item对象
        Item itemEntity = BeanUtils.copyBean(item, Item.class);
        log.info("表单-before：" + itemEntity);
        // 新增商品并获取生成的ID
        boolean flag = itemService.save(itemEntity);
        log.info("表单-after：" + itemEntity);  // save完成后 能够获取到生成的ID
        if (flag) {
            // 获取生成的商品ID
            Long itemId = itemEntity.getId();
            System.out.println("表单：" + itemEntity + "\n" + "结果：" + true);
            // 更新商品索引库 -items，传递生成的商品ID
            rabbitTemplate.convertAndSend("search.direct", "item.save_update", itemId);
        } else {
            // 处理保存失败的情况
            System.out.println("商品保存失败");
        }
    }


    @ApiOperation("更新商品")
    @PutMapping
    public void updateItem(@RequestBody ItemDTO item) {
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        item.setStatus(null);
        // 更新
        itemService.updateById(BeanUtils.copyBean(item, Item.class));
        // 更新商品索引库 -items
        rabbitTemplate.convertAndSend("search.direct", "item.save_update", item.getId());
    }

    @ApiOperation("更新商品状态")
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
    }


    @ApiOperation("根据id删除商品")
    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        itemService.removeById(id);
        // 更新商品索引库 -items
        rabbitTemplate.convertAndSend("search.direct", "item.delete", id);
    }

    @ApiOperation("批量扣减库存")
    @PutMapping("/stock/deduct")
    public void deductStock(@RequestBody List<OrderDetailDTO> items) {
        itemService.deductStock(items);
        // 获取ids集合
        List<Long> ids = items.stream().map(OrderDetailDTO::getItemId).collect(Collectors.toList());

        rabbitTemplate.convertAndSend("search.direct", "item.updateStock", ids);
    }

    @ApiOperation("批量恢复库存")
    @PutMapping("/stock/reply")
    public void replyStock(@RequestBody List<OrderDetailDTO> items) {
        itemService.replyStock(items);
        // 更新商品索引库 -items
        rabbitTemplate.convertAndSend("search.direct", "item.updateStock", items);
    }
}
